var express = require('express');
var router = express.Router();
var mongodb=require('mongodb').MongoClient;
var db_str="mongodb://localhost:27017/zz1807"
// var mongodb=require('mongodb');
// var serve = new mongodb.Server('localhost',27017,{auto_reconnect:true})
// var db=new mongodb.Db('zz1807',serve,{safe:true})

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
//注册
router.post('/register',(req,res)=>{
  console.log(req.body)
  mongodb.connect(db_str,(err, database)=>{
    database.collection('zh',(err,coll)=>{
      coll.find({username:req.body.username}).toArray((err,data)=>{
        if(data.length>0){
          res.send('2')
          database.close()
        }else{
          coll.insert(req.body,()=>{
            res.send('1')
            database.close()
          })
        }
      })
    })
  })
})
//登录
router.post('/logins',(req,res)=>{
  console.log(req.body)
  mongodb.connect(db_str,(err, database)=>{
    database.collection('zh',(err,coll)=>{
      coll.find(req.body).toArray((err,data)=>{
        if(data.length>0){
          // req.session.name=data[0].username
          res.send('1')
          database.close()
        }else{
          res.send('2')
          database.close()
        }
      })
    })
  })
})
module.exports = router;
